<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <right-toolbar @queryTable="Refresh"></right-toolbar>
    </el-row>

    <vxe-table :data="tableData.list" border :loading="tableData.loading" stripe :row-id="row => row.id">
      <template #toolbar>
        <vxe-toolbar :buttons="['export', 'import', 'search']" @search="getList"></vxe-toolbar>
      </template>

      <vxe-column field="configName" title="配置名称" align="center">
        <template #default="scope">
          <router-link :to="'/asset/nodes/index/' + scope.row.id" class="link-type">
            <span>{{ scope.row.configName }}</span>
          </router-link>
        </template>
      </vxe-column>
      <vxe-column field="status" title="状态" align="center">
        <template #default="{ row }">
          <my-switch :value="row.status===1" @click="handleStatusChange(row)"></my-switch>
        </template>
      </vxe-column>
      <vxe-column title="操作" align="center">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
        </template>
      </vxe-column>
    </vxe-table>
  </div>
</template>

<script setup>
import api from './api.js'
import { useRoute, useRouter } from "vue-router";
import MySwitch from "@/components/MySwitch.vue";

const { proxy } = getCurrentInstance();

const router = useRouter()
const route = useRoute();

const props = defineProps({
  configType: {
    type: Number,
    default: 0
  }
})

const tableData = reactive({
  loading: false,
  list: []
})

function getList() {
  tableData.loading = true;
  const query = {};
  const pageReq = { page: tableData.page, size: tableData.pageSize };
  api.list(query, pageReq, props.configType).then(response => {
    const { content, totalElements } = response;
    tableData.list = content.map(item => ({
      ...item,
      handleEdit: false 
    }));
    tableData.total = totalElements;
    tableData.loading = false;
  });
}

function handleStatusChange(row) {
  const newStatus = row.status === 1 ? 0 : 1;
  api.updateStatus(row.id, newStatus).then(res=> {
    if (res === -1) {
      return proxy.$message.error('请先编辑节点');
    }
    row.status = newStatus;
    proxy.$message.success("操作成功");
  });
}

function handleEdit(row) {
  let routeType;
  const path = route.path;
  if (path.startsWith('/asset')) {
    routeType = 'asset';
  } else {
    routeType = 'consume';
  }

  row.editing = false; 
  router.push({
    path: `/${routeType}/auditConfigNodes/index/${row.id}`
  });
}

onMounted(() => {
  getList();
})
</script>

<style lang="scss" scoped>
.app-container {
  display: flex;
  flex-direction: column;
  height: 86vh;
  overflow: hidden;
}

.vxe-table {
  flex: 1;
  overflow: auto;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
}



</style>
